#!/usr/bin/env python3
import os
import socket
import threading
from config.config import Config
from src import Session

class Server(threading.Thread):
    def __init__(self, config):
        self.listen_ip = config.listen_ip
        self.listen_port = config.listen_port
        self.running = True
        self.conn_threads = []
        self.conf = config
        super(Server, self).__init__()

    def run(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.s.bind((self.listen_ip, self.listen_port))
        self.s.listen(10)
        print("listen:", self.listen_ip," ", self.listen_port)
        self.s.settimeout(10)
        while self.running:
            try:
                conn, addr = self.s.accept()
            except socket.timeout:
                continue
            c = threading.Thread(name = str(addr), target=self.connect_client, args = (conn, addr))
            c.start()
            self.conn_threads.append(c)

        for t in self.conn_threads:
            t.join()
        print("all conn threads finished")

    def stop(self):
        self.running = False

    def connect_client(self, conn, addr):
        print('connect by', addr)
        s = Session(conn, self.conf)
        while self.running:
            s.process()
 
if __name__ == '__main__':
    c = Config()
    s = Server(c)
    s.start()
    print("start pytinyhttpd server")
    while True:
        b = input()
        if b == "q":
            print("please wait 10 second will stop")
            break
    s.stop()
    s.join()
    print("stop pytinyhttpd server")
